package com.jic.member.sms;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.RestResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpSendSms {

    private static final Logger logger = LoggerFactory.getLogger(HttpSendSms.class);

    public static RestResult<String> submitRequest(String phone, String sms, String appkey, String appsecret, String appcode, String uri) throws Throwable {
        HttpClient httpClient = null;
        HttpPost httppost = null;
        try {
            httpClient = new DefaultHttpClient();
            httppost = new HttpPost(uri);

            String smsContent = null;
            smsContent = appcodeSms(phone, sms, appkey, appsecret, appcode);

            StringEntity formEntity = new StringEntity(smsContent, "utf-8");
            httppost.setEntity(formEntity);
            HttpResponse httpresponse = null;
            httpresponse = httpClient.execute(httppost);
            HttpEntity httpEntity = httpresponse.getEntity();
            String response = EntityUtils.toString(httpEntity, "utf-8");
            logger.info(response);
            return RestResult.success(response);
        } catch (Exception e) {
            throw new Exception();
        } finally {
            if (httppost != null) {
                httppost.abort();
            }
            if (httpClient != null) {
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

    private static String appcodeSms(String phone, String sms, String appkey, String appsecret, String appcode) throws Throwable {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appkey", appkey);
        map.put("appcode", appcode);
        String timestamp = System.currentTimeMillis() + "";
        map.put("timestamp", timestamp);
        List<SmsParam> smsParam = new ArrayList<SmsParam>();
        SmsParam each = new SmsParam();
        each.setMsg(sms);
        each.setPhone(phone);
        smsParam.add(each);
        map.put("sms", smsParam);
        String sign = md5(appkey + appsecret + timestamp);
        map.put("sign", sign);
        String json = JSONObject.toJSONString(map);
        return json;
    }


    private static String md5(String param) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }


    private static String byteToHex(byte[] md5Byte) {
        String result = null;
        StringBuilder sb = new StringBuilder();
        for (byte each : md5Byte) {
            int value = each & 0xff;
            String hex = Integer.toHexString(value);
            if (value < 16) {
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }


    public static int byte4ToInteger(byte[] b, int offset) {
        return (0xff & b[offset]) << 24 | (0xff & b[offset + 1]) << 16 |
                (0xff & b[offset + 2]) << 8 | (0xff & b[offset + 3]);
    }


    public static void main(String[] args) {

//        HttpSendDemo.sendSMS("13472496351", "【高校企业云】你的短信验证码是123465",
//                "78y6vA","8FP0iT", "1000", "http://39.97.4.102:9090/sms/distinct/v1");

        JSONObject jsonObject = JSONObject.parseObject("{\"code\":\"00000\",\"desc\":\"提交成功\",\"result\":[{\"status\":\"00000\",\"phone\":\"13472496351\",\"desc\":\"提交成功\",\"uid\":\"782344a4499e47178a4ba55029397780\"}]}");

        System.out.println(jsonObject);
    }


}
